package com.jnshu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jnshu.constant.Constant;
import com.jnshu.dao.MessageMapper;
import com.jnshu.dao.UserMapper;
import com.jnshu.dao.UserMessageRelationMapper;
import com.jnshu.dto.message.*;
import com.jnshu.exception.MyException;
import com.jnshu.pojo.Message;
import com.jnshu.pojo.UserMessageRelation;
import com.jnshu.quartz.CronDateUtils;
import com.jnshu.quartz.MessageUtils;
import com.jnshu.quartz.TimeUtils;
import com.jnshu.service.MessageService;
import com.jnshu.tools.HeadUtil;
import com.jnshu.tools.PageUtil;
import com.jnshu.tools.resultUtils.PageBean;
import com.jnshu.tools.resultUtils.RUtil;
import com.jnshu.tools.resultUtils.ResultBean;
import com.jnshu.tools.resultUtils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xmp
 * @date 2019/8/6 19:53
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Autowired(required = false)
    MessageMapper messageMapper;
    @Autowired(required = false)
    UserMapper userMapper;
    @Resource(name = "scheduler")
    Scheduler scheduler;

    @Autowired(required = false)
    UserMessageRelationMapper userMessageRelationMapper;


    /**
     * 查询后台消息列表
     *
     * @param
     * @return
     */
    @Override
    public PageBean selectMessageList(MessageListBackList messageListBackList) {
        Page page = PageHelper.startPage(messageListBackList.getPageNum(), messageListBackList.getPageSize());
        List<MessageListDto> messageListDtos = messageMapper.selectMessageList(messageListBackList);
        log.info("messageList:" + messageListDtos);
        if (messageListDtos == null) {
            return RUtil.errorPage(ResultEnum.NOTHINGNESS);
        }
        return RUtil.okDefault(page.getTotal(), messageListDtos, messageListBackList.getPageNum(), messageListBackList.getPageSize());
    }

    /**
     * 分页查询列表
     */
    @Override
    public PageBean selectMessage(int pageNum, int pageSize) {
        Page page = PageHelper.startPage(pageNum, pageSize);
        List<Message> messageList = messageMapper.selectMessage();
        log.info("messageList列表查询：" + messageList);
        if (messageList == null) {
            return RUtil.errorPage(ResultEnum.NOTHINGNESS);
        }
        return RUtil.okDefault(page.getTotal(), messageList, pageNum, pageSize);
    }

    /**
     * 查询后台消息详情
     *
     * @param id
     * @return
     */
    @Override
    public MessageListDetailDto selectMessageById(long id) {
        Message message = messageMapper.selectMessageById(id);
        if (message == null) {
            throw new MyException(401, "请求用户不存在");
        }
        MessageListDetailDto messageListDetailDto = new MessageListDetailDto();
        BeanUtils.copyProperties(message, messageListDetailDto);
        return messageListDetailDto;
    }

    /**
     * 后台消息新增
     *
     * @param messageVo
     * @return
     */
    @Override
    public ResultBean insertMessage(MessageVo messageVo) throws ParseException, SchedulerException {
        Message message = new Message();
        BeanUtils.copyProperties(messageVo, message);
        long now = System.currentTimeMillis();
        log.info("现在时间：" + now);
        message.setCreateAt(now);
        message.setUpdateAt(now);
        if (messageVo.getPushType() == 0) {
            message.setStatus(0);
            long time = messageVo.getPushTime();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String date = TimeUtils.timeStampToTime(String.valueOf(time));
            log.info("Date:" + date);
            date = date.replace("T", " ");
            Date parse = format.parse(date);
            if (time <= now) {
                log.info("延时新增不能是过去的时间");
                return RUtil.error(ResultEnum.TIME_ERROR);
            }
            int result = messageMapper.insertSelective(message);
            log.info("新增文章结果：" + result);
            Map<String, Object> map = new HashMap<>();
            Long id = message.getId();
            log.info("取出来的ID：" + id);
            map.put("id", id);
            map.put("status", message.getStatus());
            MessageUtils.create(id, CronDateUtils.getCron(parse), scheduler, map);
            return RUtil.ok();
        } else {
            message.setStatus(1);
            int result = messageMapper.insertSelective(message);
            log.info("新增文章结果：" + result);
            if (result == 1) {
                return RUtil.ok();
            }
        }
        return RUtil.error(ResultEnum.FAILURE);
    }


    /**
     * 后台消息编辑
     *
     * @param messageVo
     * @return
     */
    @Override
    public ResultBean updateMessage(MessageVo messageVo) {
        log.info("messageVo:" + messageVo);
        if (messageVo.getStatus() != 0 || messageVo.getId() == null) {
            return RUtil.error(ResultEnum.Message_Status_Fail);
        }
        Message message = new Message();
        BeanUtils.copyProperties(messageVo, message);
        long now = System.currentTimeMillis();
        message.setUpdateAt(now);
        message.setUpdateBy(1L);
        long id = message.getId();
        Message message1 = messageMapper.selectMessageById(id);
        log.info("查出来的ID：" + id);
        if (message1 == null) {
            return RUtil.error(ResultEnum.NOTHINGNESS);
        }
        boolean result = messageMapper.updateByPrimaryKeySelective(message);
        if (result == true) {
            return RUtil.ok();
        }
        return RUtil.error(ResultEnum.NOTHINGNESS);
    }

    /**
     * 后台消息删除
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean deleteMessage(long id) {
        log.info("传入的ID是：" + id);
        boolean result = messageMapper.deleteByPrimaryKey(id);
        log.info("ID是否还存在：" + result);
        if (result == false) {
            log.info("公告删除失败，开始回滚");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RUtil.error(ResultEnum.NOTHINGNESS);
        }
        return RUtil.ok();
    }

    /**
     * 后台公告状态上下架变更
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public ResultBean updateMessageStatus(long id, int status) {
        log.info("公告ID：" + id + ",公告此时的状态：" + status);
        if (status == 0) {
            status = 1;
        } else {
            status = 0;
        }
        Message message = new Message();
        long now = System.currentTimeMillis();
        message.setId(id);
        message.setStatus(status);
        message.setUpdateAt(now);
        message.setPushTime(now);
        log.info("message:" + message);
        boolean result = messageMapper.updateByPrimaryKeySelective(message);
        if (result == true) {

            return RUtil.ok();
        }
        return RUtil.error(ResultEnum.FAILURE);
    }

    /**
     * 前台消息列表
     */
    @Override
    public ResultBean uSelectMessage(int pageSize, int pageNum, long userId) {

        List<Message> me = messageMapper.uSelectTime();
        List<MessageListFront> messageFront = new ArrayList<>();

        MessageListFront messageListFront = new MessageListFront();
        if (me != null) {
            for (int i = 0; i < me.size(); i++) {

                Message messages = me.get(i);
                //判断公告是新用户还是全部用户

                Integer object = messages.getObject();
                //如果是新用户就再次判断，如果是全部，就直接显示在页面
                if (object == 0) {
                    //获取公告推送时间
                    long time = messageMapper.uSelectId(messages.getId()).getPushTime();
                    log.info("time" + time);
                    //新用户创建时间
                    long userTime = userMapper.selectByTime(userId);
                    log.info("userTime" + userTime);

                    if ((time - 30 * 24 * 3600 * 1000L) < userTime) {

                        log.info("messages=====" + messages);

                        BeanUtils.copyProperties(messages, messageListFront);
                        log.info("messageListFront=====" + messageListFront);

                        //查看是否已读

                        UserMessageRelation userMessageRelation = userMessageRelationMapper.selectId(userId, messages.getId());
                        if (userMessageRelation == null) {
                            messageListFront.setNotice(0);
                        }
                        if (userMessageRelation != null) {
                            messageListFront.setNotice(1);
                        }
                        messageFront.add(messageListFront);
                    }
                }


                if (object == 1) {

                    log.info("messages=====" + messages);
                    BeanUtils.copyProperties(messages, messageListFront);
                    //查看是否已读

                    UserMessageRelation userMessageRelation = userMessageRelationMapper.selectId(userId, messages.getId());
                    if (userMessageRelation == null) {
                        messageListFront.setNotice(0);
                    }
                    if (userMessageRelation != null) {
                        messageListFront.setNotice(1);
                    }
                    messageFront.add(messageListFront);
                }
            }
            //分页
            PageUtil<MessageListFront> info = new PageUtil<>(messageFront, pageNum, pageSize);
            log.info("info=====" + info);

            return RUtil.ok(info);
        } else {
            messageListFront = null;
            return RUtil.ok(messageListFront);
        }


    }

    /**
     * 前台消息详情
     * 线上发行，取消注释
     */
    @Override
    public ResultBean uSelectId(Long id, long userId) {
        log.info("service 层传入的参数为" + id);
        Message message = messageMapper.uSelectId(id);
        log.info("数据库中的数据" + message);
        MessageFront messageFront = new MessageFront();
        BeanUtils.copyProperties(message, messageFront);

        UserMessageRelation userMessageRelations = userMessageRelationMapper.selectId(userId, message.getId());
        if (userMessageRelations == null) {
            //用户消息表中添加数据
            UserMessageRelation userMessageRelation = new UserMessageRelation();
            userMessageRelation.setUserId(userId);
            userMessageRelation.setMessageId(message.getId());
            userMessageRelation.setCreateAt(System.currentTimeMillis());
            userMessageRelation.setUpdateAt(System.currentTimeMillis());
            userMessageRelation.setCreateBy(userId);
            userMessageRelation.setUpdateBy(userId);
            userMessageRelationMapper.insertSelective(userMessageRelation);

        }
        return RUtil.ok(messageFront);
    }

    /**
     * 一键已读
     *
     * @param userId
     */
    @Override
    public ResultBean selectRead(Long userId) {

        List<Message> me = messageMapper.uSelectTime();
        List<MessageListFront> messageFront = new ArrayList<>();

        MessageListFront messageListFront = new MessageListFront();
        if (me != null) {
            for (int i = 0; i < me.size(); i++) {

                Message messages = me.get(i);
                //判断公告是新用户还是全部用户

                Integer object = messages.getObject();
                //如果是新用户就再次判断，如果是全部，就直接显示在页面
                if (object == 0) {
                    //获取公告推送时间
                    long time = messageMapper.uSelectId(messages.getId()).getPushTime();
                    log.info("time" + time);
                    //新用户创建时间
                    long userTime = userMapper.selectByTime(userId);
                    log.info("userTime" + userTime);

                    if ((time - 30 * 24 * 3600 * 1000L) < userTime) {

                        log.info("messages=====" + messages);

                        BeanUtils.copyProperties(messages, messageListFront);
                        log.info("messageListFront=====" + messageListFront);

                        //查看是否已读

                        UserMessageRelation userMessageRelation = userMessageRelationMapper.selectId(userId, messages.getId());
                        if (userMessageRelation == null) {
                            //用户消息表中添加数据
                            UserMessageRelation userMessageRelatio = new UserMessageRelation();
                            userMessageRelatio.setUserId(userId);
                            userMessageRelatio.setMessageId(messages.getId());
                            userMessageRelatio.setCreateAt(System.currentTimeMillis());
                            userMessageRelatio.setUpdateAt(System.currentTimeMillis());
                            userMessageRelatio.setCreateBy(userId);
                            userMessageRelatio.setUpdateBy(userId);
                            userMessageRelationMapper.insertSelective(userMessageRelatio);
                        }
                    }
                }

                if (object == 1) {

                    log.info("messages=====" + messages);
                    BeanUtils.copyProperties(messages, messageListFront);
                    //查看是否已读

                    UserMessageRelation userMessageRelation = userMessageRelationMapper.selectId(userId, messages.getId());
                    if (userMessageRelation == null) {
                        //用户消息表中添加数据
                        UserMessageRelation userMessageRelatio = new UserMessageRelation();
                        userMessageRelatio.setUserId(userId);
                        userMessageRelatio.setMessageId(messages.getId());
                        userMessageRelatio.setCreateAt(System.currentTimeMillis());
                        userMessageRelatio.setUpdateAt(System.currentTimeMillis());
                        userMessageRelatio.setCreateBy(userId);
                        userMessageRelatio.setUpdateBy(userId);
                        userMessageRelationMapper.insertSelective(userMessageRelatio);
                    }
                    messageFront.add(messageListFront);
                }
            }

        }
        return RUtil.ok();
    }

}
